<template>
  <a-card>
    <!-- 单据 -->
    <a-form-model ref="ruleForm" :rules="rules" :model="Form" v-bind="layout"
      ><!-- 顶部的信息 -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号">
            <a-input style="border: 0" v-model="document" disabled></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            ref="document_date"
            prop="document_date"
            label="单据日期"
          >
            <a-date-picker
              v-model="document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="发货仓库">
            <a-select
              v-model="Form.cwarehouseid_dictText"
              showSearch
              style="width: 100%"
              disabled
              @change="setdataSourceDepartment"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.cwarehouseid"
                :value="item.depotNo + '|' + item.cwarehouseid_dictText"
                >{{ item.depotNo }}
                {{ item.cwarehouseid_dictText }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>

        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="所属单位">
            <a-select
              v-model="Form.storageUnit"
              showSearch
              style="width: 100%"
              @change="setdataSourceStorageUnit"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.cwarehouseid"
                :value="item.depotNo + '|' + item.cwarehouseid_dictText"
                >{{ item.depotNo }} {{ item.cwarehouseid_dictText }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col> -->

        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="申请部门"
            ref="deptId_dictText"
            prop="deptId_dictText"
          >
            <a-select
              showSearch
              style="width: 100%"
              @change="salesDepartmentChange"
              v-model="Form.deptId_dictText"
            >
              <a-select-option
                v-for="item in saleDepartmentList"
                :key="item.value"
                :value="item.title"
                >{{ item.title }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col> -->
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="申请部门">
            <a-input v-model="Form.deptId_dictText" disabled> </a-input>

            <!-- <a-tree-select
              v-model="Form.deptId_dictText"
              show-search
              style="width: 100%"
              :tree-data="depTree"
              allow-clear
              @change="onChangeBumen2"
            ></a-tree-select> -->
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="库存组织"
            ref="ccalbodyid_dictText"
            prop="ccalbodyid_dictText"
          >
            <a-input v-model="Form.ccalbodyid_dictText" disabled> </a-input>
            <!-- <a-select
              v-model="Form.cwarehouseid_dictText"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.bodycode + '|' + item.bodyname"
              >
                {{ item.bodycode }}
                {{ item.bodyname }}
              </a-select-option>
            </a-select> -->
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="申请人" ref="applicant" prop="applicant">
            <a-input v-model="applicant" disabled> </a-input>
          </a-form-model-item>
        </a-col>
        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务员" ref="salesman" prop="salesman">
            <a-select
              v-model="Form.salesman"
              @change="getSalesmanId"
              style="width: 100%"
              showSearch
            >
              <a-select-option
                v-for="item in salesmanList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col> -->
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务员" ref="cbiztype" prop="cbiztype">
            <a-input v-model="Form.salesMan_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="客户" ref="cbiztype" prop="cbiztype">
            <a-input v-model="Form.clientId_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>
        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="客户" ref="client" prop="client">
            <a-select
              v-model="Form.client"
              @change="getClientId"
              @search="getAllClientList"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in clientList"
                :key="item.id"
                :value="item.No + '|' + item.name"
              >
                {{ item.No }} {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col> -->

        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="库管员"
            ref="cwhsmanager"
            prop="cwhsmanager"
          >
            <a-select
              @change="getcwhsmanagerId"
              v-model="Form.cwhsmanager"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col> -->

        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务类型" ref="cbiztype" prop="cbiztype">
            <a-select
              v-model="Form.sendReceiveType"
              @change="getSendReceiveTypeId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in SendReceiveList"
                :key="item.receiveSendTypeId"
                :value="
                  item.receiveSendTypeCode + '|' + item.receiveSendTypeName
                "
              >
                {{ item.receiveSendTypeCode }}
                {{ item.receiveSendTypeName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col> -->
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务类型" ref="cbiztype" prop="cbiztype">
            <a-input v-model="Form.cbiztype_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>

        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" ref="pk_corp" prop="pk_corp">
            <a-input v-model="Form.pk_corp"></a-input>
            <a-tree-select
              v-model="Form.pk_corp"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="pk_corpList"
              @change="getpk_corpId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col> -->

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="备注">
            <a-textarea
              v-model="remarks"
              style="background-color: white; color: black"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>

    <!-- 生成原单按钮组件 -->
    <BeiHuoTongZhiOrderOrigin
      @select-data="setGoodsListInfoByOrigin"
    ></BeiHuoTongZhiOrderOrigin>
    <!-- //TODO: -->
    <!-- 单据对应表格 -->
    <a-table
      :columns="columns"
      :data-source="DataSource"
      style="margin-top: 10px"
      :pagination="false"
      :scroll="{ x: 2000 }"
    >
      <!-- 仓库编码 -->
      <span slot="depotNo" slot-scope="text, record">
        <a-select
          v-model="record.depotNo"
          showSearch
          style="width: 100%"
          @change="setGoodsList(record.key)"
        >
          <a-select-option
            v-for="item in storageList"
            :key="item.depotNo"
            :value="item.depotNo + '|' + item.cwarehouseid_dictText"
          >
            {{ item.depotNo }} {{ item.cwarehouseid_dictText }}
          </a-select-option>
        </a-select>
      </span>
      <!-- 所属单位 -->

      <span slot="StorageUnit" slot-scope="text, record">
        <a-select
          v-model="record.StorageUnit"
          showSearch
          style="width: 100%"
          @change="getStorageUnitId(record.key)"
        >
          <a-select-option
            v-for="item in storageList"
            :key="item.depotNo"
            :value="item.depotNo + '|' + item.cwarehouseid_dictText"
          >
            {{ item.depotNo }} {{ item.cwarehouseid_dictText }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 存货编码 -->
      <span slot="inventoryNo" slot-scope="text, record">
        <a-select
          v-model="record.inventoryNo"
          style="width: 100%"
          @change="getInventoryInfo(record.key)"
          @search="handleInventoryInfoSearch"
          showSearch
        >
          <a-select-option
            v-for="item in goodsList"
            :key="item.inventoryId"
            :value="item.inventoryNo + '|' + item.inventoryName"
          >
            {{ item.inventoryNo }} {{ item.inventoryName }}
            {{ item.specifications }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 辅助单位 -->
      <span slot="auxiliaryUnit" slot-scope="text, record">
        <a-select
          v-model="record.auxiliaryUnit"
          style="width: 100%"
          @change="disableUnit(record.key)"
          showSearch
        >
          <a-select-option
            v-for="item in Auxiliary_Unitlist"
            :key="item.value"
            :value="item.title + '|' + item.value"
          >
            {{ item.value }} {{ item.title }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 申请数量 -->
      <span slot="quantity" slot-scope="text, record">
        <a-input v-model="record.quantity" :min="0" :step="0.001" />
      </span>

      <!-- 包装形式 字典表-->
      <span slot="packagingForm" slot-scope="text, record">
        <a-select v-model="record.packagingForm" style="width: 100%">
          <a-select-option
            v-for="(item, index) in packingList"
            :key="index"
            :value="item.title"
          >
            {{ item.title }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 发货时间 -->
      <span slot="deliveryDate" slot-scope="text, record">
        <a-date-picker
          @change="FormatdeliveryTime(record.key)"
          v-model="record.deliveryDate"
        />
      </span>

      <!-- 是否赠品 -->
      <span slot="giveaway" slot-scope="text, record">
        <a-select
          v-model="record.giveaway"
          @change="getGiveAwayText(record.key)"
          style="width: 100%"
        >
          <a-select-option
            v-for="item in giveAwayList"
            :key="item.title"
            :value="item.value"
          >
            {{ item.title }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 备注 -->
      <span slot="mark" slot-scope="text, record">
        <a-input v-model="record.mark" />
      </span>
      <!-- 操作 -->
      <!-- <template slot="action" slot-scope="text, record">
        <span v-if="record.isNew">
          <a @click="cancle(record.key)">取消</a>
        </span>
        <span v-else>
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="DeleteInfo(record.key)"
          >
            <template slot="title">
              <p>确定删除？</p>
            </template>
            <a type="danger"> 删除 </a>
          </a-popconfirm>
        </span>
      </template> -->
    </a-table>
    <!-- <a-button
      style="width: 100%; margin-top: 16px; margin-bottom: 8px"
      type="dashed"
      icon="plus"
      @click="newMember"
      >添加</a-button
    > -->
    <!-- 备货组意见 -->
    <a-descriptions
      title
      bordered
      :column="{ xxl: 3, xl: 3, lg: 3, md: 3, sm: 1, xs: 1 }"
      style="text-align: right"
      size="small"
    >
      <a-descriptions-item label="备货组意见" :span="3">
        <div style="height: 60px; width: 800px"></div>

        <div>
          <a-row>
            <a-col :span="9"></a-col>
            <a-col :span="9">签名：</a-col>
            <a-col :span="6">日期：</a-col>
          </a-row>
        </div>
      </a-descriptions-item>
      <a-descriptions-item label="销售调度人员" :span="3">
        <div style="height: 60px; width: 800px"></div>

        <div>
          <a-row>
            <a-col :span="9"></a-col>
            <a-col :span="9">签名：</a-col>
            <a-col :span="6">日期：</a-col>
          </a-row>
        </div>
      </a-descriptions-item>
      <a-descriptions-item label="仓库管理员" :span="3">
        <div style="height: 60px; width: 800px"></div>

        <div>
          <a-row>
            <a-col :span="9"></a-col>
            <a-col :span="9">签名：</a-col>
            <a-col :span="6">日期：</a-col>
          </a-row>
        </div>
      </a-descriptions-item>
    </a-descriptions>

    <workflow
      :duty_name="duty_name"
      @submit-assignee="Submit"
      @reset-form="resetForm"
      ref="workflow"
    ></workflow>
  </a-card>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

import workflow from "@/components/common/workFlow";
import BeiHuoTongZhiOrderOrigin from "./BeiHuoTongZhiOrderOrigin.vue";

import { BeiHuoTongZhiHttp } from "@/services/modules/ChuKuGuanLi/XiaoShouChuKu/BeiHuoTongZhi";
const bhtzjHttp = new BeiHuoTongZhiHttp(); // 备货通知

import moment from "moment";

// 物品信息表格
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },

  // {
  //   key: "depotNo",
  //   dataIndex: "depotNo",
  //   align: "center",
  //   title: "仓库编码",
  //   // scopedSlots: { customRender: "depotNo" },
  //   width: "280px",
  // },
  {
    title: "仓库名称",
    key: "cwarehouseid_dictText",
    dataIndex: "cwarehouseid_dictText",
    align: "center",
  },
  // {
  //   title: "所属单位",
  //   key: "StorageUnit",
  //   dataIndex: "StorageUnit",
  //   align: "center",
  //   scopedSlots: { customRender: "StorageUnit" },
  //   width: "280px",
  // },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    // scopedSlots: { customRender: "inventoryNo" },
    // width: "500px",
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "specifications",
    key: "specifications",
    align: "center",
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    align: "center",
  },
  // {
  //   title: "辅助单位",
  //   key: "auxiliaryUnit",
  //   dataIndex: "auxiliaryUnit",
  //   align: "center",
  //   scopedSlots: { customRender: "auxiliaryUnit" },
  // },

  {
    title: "申请数量",
    dataIndex: "quantity",
    key: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },

  {
    title: "包装形式",
    key: "packagingForm",
    dataIndex: "packagingForm",
    align: "center",
    scopedSlots: { customRender: "packagingForm" },
  },
  {
    title: "发货时间",
    key: "deliveryDate",
    dataIndex: "deliveryDate",
    align: "center",
    width: "180px",
    scopedSlots: { customRender: "deliveryDate" },
  },
  {
    title: "源单号",
    key: "documentNo",
    dataIndex: "documentNo",
    align: "center",
  },
  {
    title: "是否赠品",
    key: "giveaway",
    dataIndex: "giveaway",
    align: "center",
    width: "120px",
    scopedSlots: { customRender: "giveaway" },
  },
  // {
  //   title: "备注",
  //   key: "mark",
  //   dataIndex: "mark",
  //   align: "center",
  //   scopedSlots: { customRender: "mark" },
  // },
  // {
  //   title: "操作",
  //   dataIndex: "action",
  //   key: "action",
  //   align: "center",
  //   scopedSlots: { customRender: "action" },
  // },
];

export default {
  components: {
    BeiHuoTongZhiOrderOrigin,
    workflow,
  },

  data() {
    return {
      // 校验
      rules: {
        // 单据日期
        // document_date: [
        //   {
        //     required: true,
        //     message: "请填写单据日期",
        //     trigger: "change",
        //   },
        // ],
        // 申请部门
        deptId_dictText: [
          {
            required: true,
            message: "请填写申请部门",
            trigger: "change",
          },
        ],
        // 申请人
        // applicant: [
        //   {
        //     required: true,
        //     message: "请填写申请人",
        //     trigger: "change",
        //   },
        // ],
        // 业务员
        salesman: [
          {
            required: true,
            message: "请填写业务员",
            trigger: "change",
          },
        ],
        // 客户
        client: [
          {
            required: true,
            message: "请填写客户",
            trigger: "change",
          },
        ],
        // 库管员
        cwhsmanager: [
          {
            required: true,
            message: "库管员不能为空！",
            trigger: "change",
          },
        ],

        // 业务类型
        // cbiztype: [
        //   {
        //     required: true,
        //     message: "业务类型不能为空！",
        //     trigger: "change",
        //   },
        // ],
        // 库存组织
        cwarehouseid_dictText: [
          {
            required: true,
            message: "库存组织不能为空！",
            trigger: "change",
          },
        ],
        // 公司
        pk_corp: [
          {
            required: true,
            message: "公司不能为空！",
            trigger: "change",
          },
        ],
      },

      // ----- 申请的表单内容信息 -----
      document: "", // 单据号
      document_date: moment().format("YYYY-MM-DD"), // 单据日期
      applicant: this.$store.state.user.info.username, // 申请人
      applicantId: this.$store.state.user.info.id, // 申请人id

      deptId_dictText: "", // 部门名称

      Form: {
        cwarehouseid_dictText: "", // 仓库名称
        depotNo: "", // 仓库编号
        cwarehouseid: "", // 仓库Id

        storageUnit: "", // 所属单位名称
        StorageUnitId: "", // 所属单位Id
        StorageUnitNo: "", // 所属单位编号
        deptId_dictText: "", // 部门名称
        deptId: "", // 部门id

        client: "", // 客户名称
        clientId: "", // 客户Id

        salesman: "", // 业务员
        salesmanId: "", // 业务员

        pk_calbodyId: "", // 库存组织Id
        pk_calbody: "",
        cbiztype: "", //
        // sailingSchedule // 船期

        // 公司
      },
      remarks: "", //备注
      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      // 字典表等数据
      storageList: [], // 仓库列表
      saleDepartmentList: [], // 部门列表
      ApplyPersonList: [], // 申请人列表
      salesmanList: [], // 业务员列表
      clientList: [], // 客户列表

      InventoryOrganizationList: [], // 库存组织列表
      UserList: [], // 库管员列表
      workNoList: [], // 判重使用
      pk_corpList: [], // 公司列表

      Auxiliary_Unitlist: [], // 辅助单位列表
      packingList: [], // 包装形式列表
      giveAwayList: [], // 是否赠品列表
      goodsList: [], // 物品列表
      depTree: [], // 核算部门列表

      // ------- 表格 --------
      columns,
      DataSource: [],
      selectedRowKeys: [],

      // 工作流组件数据
      duty_name: "备货流程",
    };
  },
  // 生命周期函数
  mounted() {
    // this.InitDataSource(); // 初始化信息
    this.getApplyOrder(); // 获取申请单号
    this.getSaleDepartmentList(); // 销售部门
    this.getApplyStorage(); // 获取仓库
    this.getApplyUserInfo(); // 通过角色名称查询人员信息
    this.sendDutyName(); // 工作流方法
    this.getPackagingTypeList(); // 包装形式列表
    this.getGiveawayList(); // 是否赠品
    this.getAuxiliary_Unitlist(); // 辅助单位
    this.getSalesmanList(); // 获取销售业务员
    this.getSyncInventoryOrganizationList(); //获取库存组织列表
    this.getpk_corpList(); //获取公司列表
    this.getDeparmentTree(); // 获取核算部门树
  },
  methods: {
    //根据提交部门的title，找到对应value,并给部门id赋值
    onChangeBumen2(a) {
      console.log("a", a);
      let array = a.split("|");
      this.Form.deptId = array[0];
      this.Form.deptId_dictText = array[1];
    },
    // 获取核算部门列表
    getDeparmentTree() {
      // console.log("获取部门列表hanshu===");
      comHttp.getDepartmentTreeNew().then((res) => {
        if (res.success) {
          // console.log("获取部门树", res);
          this.depTree = res.result;

          this.getYongYou(this.depTree);
          // console.log("this.depTree", this.depTree);
        }
      });
    },
    //将用友中采购部门的格式转换成Tree识别的格式
    getYongYou(tree) {
      tree.forEach((element) => {
        element["title"] = element.deptcode + " " + element.deptname;
        element["value"] = element.pkDeptdoc + "|" + element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.getYongYou(element.children);
        }
      });
    },

    /* ---------------------  基本信息 ---------------------------- */
    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value, options) {
      this.Form.pk_calbodyId = options.key;
    },
    // 获取公司
    getpk_corpList() {
      comHttp.getpk_corpList().then((res) => {
        console.log("公司", res);
        this.pk_corpList = res.result;
        this.changeCorpData(this.pk_corpList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.unitcode + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;
        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },
    // 获取公司Id
    getpk_corpId(value, label, extra) {
      console.log(extra);
    },

    // 库管员列表
    getcwhsmanagerId() {},

    // 查询人员信息列表
    searchUserInfoList(value) {
      // this.UserList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },

    // !下拉框搜索
    handleInventoryInfoSearch(value) {
      if (value == "") {
        this.$message.error("请输入要搜索的物品名称");
      } else {
        this.goodsList = [];
        let queryPath = "?name=" + value;
        comHttp.getSearchInventoryInformationFile(queryPath).then((res) => {
          console.log("res", res.result.length);
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              inventoryId: res.result[i].id, // 存货 id
              inventoryName: res.result[i].inventoryName,
              inventoryNo: res.result[i].inventoryNo,
              specifications: res.result[i].specificationsModel,
              unit: res.result[i].unit,
            };
            this.goodsList.push(data);
          }
        });
      }
    },

    //

    //-------------列表及众多加载数据 ----------
    // 表格添加新的一条记录
    newMember() {
      this.DataSource.push({
        key: this.DataSource.length + 1,
        isNew: true,

        depotNo: "", // 仓库编码
        cwarehouseid_dictText: "", // 仓库名称
        cwarehouseid: "", // 仓库Id

        StorageUnit: "", // 所属单位
        StorageUnitNo: "", // 所属单位编码
        StorageUnitId: "", // 所属单位Id

        inventoryNo: "", // 存货编码
        inventoryName: "", // 存货名称
        inventoryId: "", // 存货Id
        specifications: "", // 规格型号
        unit: "", // 单位
        auxiliaryUnit: "", // 辅助单位
        auxiliaryUnitId: "", // 辅助单位Id
        quantity: 0, // 申请数量
        actualQuantity: "", // 实发数量

        packagingForm: "", // 包装形式

        deliveryDate: moment().format("YYYY-MM-DD"), // 发货时间
        sourceNo: "", // 源单号
        giveaway: "", // 是否赠品
        mark: "", // 备注
        goodsList: [], // 物品列
      });
    },
    // 表格取消一行
    cancle(key) {
      // console.log(key);
      if (this.DataSource.length > 1) {
        this.DataSource.splice(key - 1, 1);
        for (let i = key - 1; i < this.DataSource.length; i++) {
          this.DataSource[i].key = i + 1;
        }
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },
    // 提交
    Submit(Path) {
      console.log("这个是要提交的数据", this.Form);
      // 校验
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // query 传参
          let queryPath =
            Path +
            "&requisitionNo=" +
            this.document + // 单据号
            "&applicationDate=" +
            moment(this.document_date).format("YYYY-MM-DD") + // 单据日期
            "&applicationDept=" +
            this.Form.deptId + // 申请部门
            "&applicationDept_text=" +
            this.Form.deptId_dictText + // 申请部门
            "&applicant=" +
            this.applicantId + // 申请人Id
            "&applicantId_text=" +
            this.applicant + // 申请人
            "&salesman=" +
            this.Form.salesMan + // 业务员Id
            "&saleman_text=" +
            this.Form.salesMan_dictText + // 业务员
            "&clientId=" +
            this.Form.clientId + // 客户Id
            "&clientId_text=" +
            this.Form.clientId_dictText + // 客户
            "&pkCalbody=" +
            this.Form.ccalbodyid + // 库存组织
            "&pkCalbody_text=" +
            this.Form.ccalbodyid_dictText + // 库存组织
            "&cbiztype=" +
            this.Form.cbiztype + // 业务类型
            "&cbiztype_text=" +
            this.Form.cbiztype_dictText + // 业务流程
            "&applicationDepot=" +
            this.Form.cwarehouseid + // 发货仓库
            "&applicationDepot_text=" +
            this.Form.cwarehouseid_dictText + // 发货仓库
            "&saleOrderAddId=" +
            this.Form.id + // 销售订单外键Id
            "&remarks=" +
            this.remarks + // 备注
            // 标志位
            "&sign=0" +
            "&mark=0";

          const newData = this.DataSource;
          let AllGoods = [];
          for (let i = 0; i < newData.length; i++) {
            let data = {
              // 申请仓库Id
              // applicationDepot_text: newData[i].cwarehouseid_dictText, // 申请仓库名称
              // applicationDepotCode: newData[i].depotNo, // 申请仓库编码

              // depotId: this.Form.cwarehouseid, // 仓库id
              // storageUnit: newData[i].StorageUnitId, // 所属单位Id
              // storageUnit_text: newData[i].StorageUnit, // 所属单位名字
              saleOrderRequestId: newData[i].id,
              inventoryNo_text: newData[i].inventoryNo, // 存货编码
              inventoryNane: newData[i].inventoryName, // 存货名称
              inventoryNo: newData[i].inventoryId, // 存货id

              standardModel: newData[i].specifications, // 规格
              unit: newData[i].unit, // 单位

              // auxiliaryUnit_text: newData[i].auxiliaryUnit, // 辅助单位名称
              // auxiliaryUnit: parseInt(newData[i].auxiliaryUnitId), // 辅助单位id

              applyNumber: newData[i].quantity, // 申请数量
              // actualQuantity: newData[i].actualQuantity, // 实发数量
              // actualQuantity:"", // 实发数量

              packagingForm_text: newData[i].packagingForm, // 包装形式名称
              // 包装形式Id
              deliveryTime: newData[i].deliveryDate, // 发货时间
              sourceNo_text: newData[i].documentNo, // 源单号

              giveaway_text: newData[i].giveaway_text, // 是否赠品
              giveaway: newData[i].giveaway, // 是否赠品Id

              // mark: newData[i].mark, // 备注
            };
            AllGoods.push(data);
          }
          console.log("要提交的表格数据:::", queryPath, AllGoods);

          // 提交过去的数据
          bhtzjHttp.StockNoticeSave(queryPath, AllGoods).then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.$message.success("提交成功");
              this.resetForm();
            } else {
              this.$message.error("提交失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 重置
    resetForm() {
      this.document = ""; // 单据号
      this.document_date = moment().format("YYYY-MM-DD"); // 单据日期
      this.Form = {
        cwarehouseid_dictText: "", // 仓库名称
        depotNo: "", // 仓库编号
        cwarehouseid: "", // 仓库Id
        storageUnit: "", // 所属单位名称
        StorageUnitId: "", // 所属单位Id
        StorageUnitNo: "", // 所属单位编号

        deptId: "", // 部门id
        client: "", // 客户名称
        clientId: "", // 客户Id
        applicant: this.$store.state.user.info.username, // 申请人
        applicantId: this.$store.state.user.info.id, // 申请人id
        salesman: "", // 业务员
        salesmanId: "", // 业务员
        remarks: "", //备注
      };

      this.DataSource = [];
      this.getApplyOrder();
      console.log("123");
    },
    // 默认设置五行，让用户方便添加

    // ------------- 已完成 -------------
    // 获取单号
    getApplyOrder() {
      comHttp.getOrder("?string=BHSQ-").then((res) => {
        this.document = res.message;
      });
    },
    // 表格选择事件,
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    // 包装形式列表
    getPackagingTypeList() {
      comHttp.getPackagingTypeList().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.packingList.push(data);
        }
      });
    },
    // 获取存货信息
    getInventoryInfo(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];

      // 分割字符串,取出来存货编码
      let array = target.inventoryNo.split("|");
      target.inventoryNo = array[0]; // 赋值给存货编码
      target.inventoryName = array[1]; // 赋值给存货名称

      for (let i = 0; i < this.goodsList.length; i++) {
        if (target.inventoryNo == this.goodsList[i].inventoryNo) {
          target.inventoryId = this.goodsList[i].inventoryId;
          target.specifications = this.goodsList[i].specifications; // 存货规格名称
          target.unit = this.goodsList[i].unit; // 存货单位
          break;
        }
      }
      target.giveaway = 2; // 是否赠品 , 默认为否
      target.giveaway_text = "否"; // 是否赠品 , 默认为否
    },
    // 获取物品信息,后期可能会修改为根据仓库id获取物品信息，因为物品信息是根据仓库id来的！！！！！
    // getGoodSInfo(id) {
    //   let goodsList = [];
    //   comHttp.getInventoryInformation("?depotNo=" + id).then((res) => {
    //     console.log("获取存货信息:::::", res);
    //     for (let i = 0; i < res.result.length; i++) {
    //       let data = {
    //         inventoryId: res.result[i].id, // 存货 id
    //         inventoryName: res.result[i].inventoryName,
    //         inventoryNo: res.result[i].inventoryNo,
    //         specifications: res.result[i].specificationsModel,
    //         unit: res.result[i].unit,
    //       };
    //       goodsList.push(data);
    //     }
    //     console.log(goodsList);
    //   });
    //   return goodsList;
    // },
    // 表单仓库点击按钮 -------- 上方选择仓库后，下方物品都填入该仓库
    setdataSourceDepartment(value, options) {
      console.log("仓库", this.Form);
      this.Form.cwarehouseid = options.key;
      let array = value.split("|");
      this.Form.cwarehouseid_dictText = array[1];
      let key = options.key; // 仓库Id

      // // 获取物品信息列表,根据仓库编码
      // // let goodsList = this.getGoodSInfo(key);
      // // 根据仓库查询物品信息,并存储到相应的物品信息表中

      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].depotNo = array[0];
        this.DataSource[i].cwarehouseid_dictText = array[1];
        this.DataSource[i].cwarehouseid = key;
      }
      // console.log("赋值好的表格内容:::::", this.DataSource);
    },

    // 设置存货列表
    setGoodsList(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.depotNo.split("|");
      target.depotNo = array[0]; // 仓库id
      target.cwarehouseid_dictText = array[1]; // 仓库名称

      // console.log('仓库列表',this.storageList)

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];

      target.cwarehouseid = SotrageInfo.cwarehouseid;
      // let goodsList = this.getGoodSInfo();
      // target.goodsList = goodsList;
      console.log("仓库", target);
    },
    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getStorageName().then((res) => {
        //   // let tree = this.resetTree(res.result);
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            cwarehouseid: res.result[i].pkStordoc,
            cwarehouseid_dictText: res.result[i].storname,
            depotNo: res.result[i].storcode,
          };
          this.storageList.push(data);
        }
      });
    },
    // 设置所属单位, 上面表单触发事件
    setdataSourceStorageUnit(value, options) {
      let array = value.split("|");
      this.Form.storageUnit = array[1];
      // console.log(array[0]);
      let key = options.key;
      console.log("赋值好的表格内容:::::", options.key);

      // option.key
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].StorageUnitNo = array[0];
        this.DataSource[i].StorageUnit = array[1];
        this.DataSource[i].StorageUnitId = key;
      }
      console.log("赋值好的表格内容:::::", this.DataSource);
    },

    // 获取所属单位,表格触发事件
    getStorageUnitId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.StorageUnit.split("|");
      target.StorageUnitNo = array[0]; // 仓库编码
      target.StorageUnit = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.StorageUnitId = SotrageInfo.cwarehouseid;
    },
    // 获取销售部门列表
    getSaleDepartmentList() {
      this.saleDepartmentList = [];
      comHttp.getSaleDepartment().then((res) => {
        console.log("获取所属单位", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.saleDepartmentList.push(data);
        }
      });
    },
    // 获取批次号
    getBatchNumberList(id) {
      comHttp.getBatchNumberList("?inventoryId=" + id).then((res) => {
        console.log(res);
      });
    },
    // 获取是否赠品列表
    getGiveawayList() {
      comHttp.getWarehouseGiveaway().then((res) => {
        console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: parseInt(res.result[i].value),
            title: res.result[i].title,
          };
          this.giveAwayList.push(data);
        }
      });
    },
    // 获取辅助单位
    getAuxiliary_Unitlist() {
      comHttp.getAuxiliaryUnit().then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            title: res.result[i].title,
            value: parseInt(res.result[i].value),
          };
          this.Auxiliary_Unitlist.push(data);
        }
        // console.log("获取辅助单位列表::::",  this.Auxiliary_Unitlist);
      });
    },
    // 选择辅助单位后,单位置空
    disableUnit(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log(target);

      let array = target.auxiliaryUnit.split("|");
      target.auxiliaryUnit = array[0];
      target.auxiliaryUnitId = array[1];
      // console.log("选择辅助单位的记录", target);

      if (target.inventoryNo == "") {
        this.$message.error("请先选择存货信息");
        target.auxiliaryUnit = "";
        target.auxiliaryUnitId = "";
      } else {
        target.unit = "";
      }
    },
    // 部门下拉框选择
    salesDepartmentChange(value, option) {
      this.Form.deptId = option.key;
      console.log("选择的值::::", this.Form.deptId);
    },
    // 工作流
    sendDutyName() {
      this.$refs.workflow.getProcessName();
    },
    // 获取申请人
    getApplyUserInfo() {
      const roleName = "出库申请人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.ApplyPersonList.push(data);
        }
        console.log(this.ApplyPersonList);
      });
    },

    // 申请人赋值
    getApplicantId(value, options) {
      this.Form.applicantId = options.key;
      let array = value.split("|");
      this.Form.applicant = array[1];
    },

    // 获取销售员列表
    getSalesmanList() {
      const roleName = "出库申请人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.salesmanList.push(data);
        }
      });
    },
    // 获取销售员Id
    getSalesmanId(value, options) {
      this.Form.salesmanId = options.key;
      let array = value.split("|");
      this.Form.salesman = array[1];
    },

    // 格式化发货时间
    FormatdeliveryTime(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      target.deliveryDate = moment(target.deliveryDate).format("YYYY-MM-DD");
      console.log("修改好的时间为:::::", target.deliveryDate);
    },

    // 获取客户列表
    getAllClientList(value) {
      console.log("客户列表", value);

      if (value != "") {
        comHttp.getSearchClientList("?name=" + value).then((res) => {
          console.log("客户列表", res);
          this.clientList = [];
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              No: res.result[i].customerCode,
              id: res.result[i].id,
              name: res.result[i].name,
            };
            this.clientList.push(data);
          }
          console.log("客户列表", this.clientList);
        });
      }
    },
    // 获取客户Id
    getClientId(value, option) {
      console.log(value);
      this.Form.clientId = option.key;
      let array = value.split("|");
      this.Form.client = array[1];
    },

    // 获取
    getGiveAwayText(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      for (let i = 0; i < this.giveAwayList.length; i++) {
        if (this.giveAwayList[i].value == target.giveaway) {
          target.giveaway_text = this.giveAwayList[i].title;
          break;
        }
      }
      console.log(target);
    },

    // // 初始化信息
    // InitDataSource() {
    //   this.DataSource = [];
    //   this.DataSource = this.setDataSource(1);
    // },

    // 默认设置五行，让用户方便添加
    setDataSource(size) {
      let tmpArray = [];
      for (let i = 0; i < size; i++) {
        let data = {
          key: i + 1,
          isNew: true,
          depotNo: "", // 仓库编码
          cwarehouseid_dictText: "", // 仓库名称
          cwarehouseid: "", // 仓库Id
          StorageUnit: "", // 所属单位
          StorageUnitNo: "", // 所属单位编码
          StorageUnitId: "", // 所属单位Id
          inventoryNo: "", // 存货编码
          inventoryName: "", // 存货名称
          inventoryId: "", // 存货Id
          specifications: "", // 规格型号
          unit: "", // 单位

          quantity: 0, // 申请数量
          actualQuantity: "", // 实发数量
          packagingForm: "", // 包装形式
          deliveryDate: moment().format("YYYY-MM-DD"), // 发货时间
          sourceNo: "", // 源单号

          auxiliaryUnit: "", // 辅助单位
          auxiliaryUnitId: "", // 辅助单位Id
          giveaway: "", // 是否赠品
          giveaway_text: "",

          mark: "", // 备注
          goodsList: [], // 物品列
        };
        tmpArray.push(data);
      }
      return tmpArray;
    },

    // 通过源单生成数据
    setGoodsListInfoByOrigin(data) {
      console.log("传递过来的数据:::::", data);

      this.Form = data;
      this.DataSource = data.goodsList;

      // cwarehouseid

      // 重新规整序号
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].key = i + 1;
        this.DataSource[i].giveaway = data.giveaway;
        this.DataSource[i].giveaway_text = data.giveaway_dictText;
        this.DataSource[i].documentNo = data.documentNo;
        this.DataSource[i].auxiliaryUnit_text = "";
        this.DataSource[i].auxiliaryUnit = "";
        this.$set(this.DataSource[i], "packagingForm", "");
        this.DataSource[i].packagingForm = "";
        this.DataSource[i].cwarehouseid_dictText = data.cwarehouseid_dictText;
      }
    },

    // 验证文件状态
    getFildStatus(id) {
      const data = this.DataSource.filter((item) => id === item.id)[0];
      if (data) {
        return data;
      } else {
        return {
          validateStatus: "error",
        };
      }
    },
  },
};
</script>
<style></style>
